package itpenguin.review.util;

import itpenguin.common.PMFactory;
import itpenguin.review.entities.Item;

import java.io.IOException;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class ReviewUtil {
	public static String getItemId(HttpServletRequest req) throws ServletException {
		String pathinfo = req.getPathInfo();
		String itemId = null;
		
		if (pathinfo == null)
		{
			throw new ServletException();
		}
		
		String[] uri = req.getPathInfo().split("/");
		if (uri.length == 2)
		{
			itemId = uri[1];
		} else {
			throw new ServletException();
		}
		return itemId;
	}

	public static Item getItem(String itemId)
			throws IOException {

		PersistenceManager pm = null;
		try {
			pm = PMFactory.getInstance().getPersistenceManager();
			Key k = KeyFactory.createKey(Item.class.getSimpleName(), itemId); 
			Item item = null;
			
			try {
				item = pm.getObjectById(Item.class, k);
			} catch (JDOObjectNotFoundException e) {
				return null;
			}
			return pm.detachCopy(item);
		} finally {
			pm.close();
		}
	}
	
}
